package service;

import Dao.BillDao;
import domain.Bill;
import domain.Cart;
import domain.Product;
import utils.jdbcUtilByDruid;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BillService {
    private BillDao billDao = new BillDao();
    private CartService cartService = new CartService();//结账时对购物车进行清空操作
    private ProductService productService = new ProductService();//得到商品的其他信息，比如金额
    private ClientsService clientsService = new ClientsService();//对用户的累计消费金额进行修改
    //生成账单表(付款的东西全部添加到账单表里面)
    public void addBill(Integer productID,Integer ClientID,String paymentMode) throws SQLException,
            IOException, NoSuchFieldException, ClassNotFoundException,
            InstantiationException, IllegalAccessException {
        Connection connection=null;
        try {
            //获取连接，开启事务
            connection= jdbcUtilByDruid.getConnection();
            connection.setAutoCommit(false);//手动提交
            if (!cartService.isExist(productID,ClientID)) {
                System.out.println("该商品不在购物车~");
                return;
            }
            Cart cart = cartService.findCartRecordById(productID,ClientID);
            Product product=productService.findProductById(productID);
            int i=billDao.update("INSERT INTO Bill (productName,myQuantity,money,paymentTime," +
                            "paymentMode,ClientID) VALUES (?,?,?,now(),?,?) ",
                    cart.getProductName(),cart.getMyQuantity(),
                    cart.getMyQuantity()*cart.getRetailPrice(),
                    paymentMode,cart.getClientID());
            //对商品表的数量进行更新，并且当现存数量-购买数量等于0的时候，商品下架
            clientsService.updateTotalConsumption(cart.getRetailPrice()*cart.getMyQuantity(), ClientID);
            cartService.removeCart(productID,ClientID);
            productService.updateQuantity(productID,cart.getMyQuantity());
            //没有异常就提交
            connection.commit();
        } catch (Exception e) {
          try{
              connection.rollback();//若出现异常，回滚事务
          }catch (SQLException throwables){
          throw new RuntimeException(throwables);}
        }
    }

    //查看用户的购物历史
    public List<Bill> getAllBill(Integer ClientID) throws SQLException, ClassNotFoundException,
            InstantiationException,
            IllegalAccessException, IOException, NoSuchFieldException {
        return billDao.queryMulti("select * from Bill " +
                "where ClientID=? ", Bill.class,ClientID);
    }

}
